[[...path]].page.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import { isClient, pagePathUtils, pathUtils } from '@growi/core';
  4. import ExtensibleCustomError from 'extensible-custom-error';
  5. import {
  6. NextPage, GetServerSideProps, GetServerSidePropsContext,
  7. } from 'next';
  8. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  9. import dynamic from 'next/dynamic';
  10. import Head from 'next/head';
  11. import { useRouter } from 'next/router';
  12. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  13. // import { PageComments } from '~/components/PageComment/PageComments';
  14. // import { useTranslation } from '~/i18n';
  15. import { CrowiRequest } from '~/interfaces/crowi-request';
  16. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  17. // import { useIndentSize } from '~/stores/editor';
  18. // import { useRendererSettings } from '~/stores/renderer';
  19. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  20. import { CustomWindow } from '~/interfaces/global';
  21. import { IPageWithMeta } from '~/interfaces/page';
  22. import { GrowiRendererConfig, RendererSettings } from '~/interfaces/services/renderer';
  23. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  24. import { PageModel, PageDocument } from '~/server/models/page';
  25. import UserUISettings, { UserUISettingsDocument } from '~/server/models/user-ui-settings';
  26. import Xss from '~/services/xss';
  27. import { useSWRxCurrentPage, useSWRxPageInfo, useSWRxPage } from '~/stores/page';
  28. import { useRendererSettings } from '~/stores/renderer';
  29. import {
  30. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  31. } from '~/stores/ui';
  32. import loggerFactory from '~/utils/logger';
  33. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  34. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  35. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  36. import { BasicLayout } from '../components/BasicLayout';
  37. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  38. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  39. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  40. import {
  41. useCurrentUser, useCurrentPagePath,
  42. useOwnerOfCurrentPage, useIsLatestRevision,
  43. useIsForbidden, useIsNotFound, useIsTrashPage, useShared, useShareLinkId, useIsSharedUser, useIsAbleToDeleteCompletely,
  44. useAppTitle, useSiteUrl, useConfidential, useIsEnabledStaleNotification,
  45. useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsMailerSetup,
  46. useAclEnabled, useIsAclEnabled, useHasSlackConfig, useDrawioUri, useHackmdUri,
  47. useNoCdn, useEditorConfig, useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname, useIsSlackConfigured, useGrowiRendererConfig,
  48. } from '../stores/context';
  49. import { useXss } from '../stores/xss';
  50. import {
  51. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  52. } from './commons';
  53. // import { useCurrentPageSWR } from '../stores/page';
  54. const logger = loggerFactory('growi:pages:all');
  55. const { isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage } = pagePathUtils;
  56. const { removeHeadingSlash } = pathUtils;
  57. const IdenticalPathPage = (): JSX.Element => {
  58. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  59. return <IdenticalPathPage />;
  60. };
  61. type Props = CommonProps & {
  62. currentUser: string,
  63. pageWithMetaStr: string,
  64. // pageUser?: any,
  65. // redirectTo?: string;
  66. // redirectFrom?: string;
  67. // shareLinkId?: string;
  68. isLatestRevision?: boolean
  69. isIdenticalPathPage?: boolean,
  70. isForbidden: boolean,
  71. isNotFound: boolean,
  72. // isAbleToDeleteCompletely: boolean,
  73. isSearchServiceConfigured: boolean,
  74. isSearchServiceReachable: boolean,
  75. isSearchScopeChildrenAsDefault: boolean,
  76. isSlackConfigured: boolean,
  77. // isMailerSetup: boolean,
  78. isAclEnabled: boolean,
  79. // hasSlackConfig: boolean,
  80. // drawioUri: string,
  81. // hackmdUri: string,
  82. // noCdn: string,
  83. // highlightJsStyle: string,
  84. // isAllReplyShown: boolean,
  85. // isContainerFluid: boolean,
  86. // editorConfig: any,
  87. isEnabledStaleNotification: boolean,
  88. // isEnabledLinebreaks: boolean,
  89. // isEnabledLinebreaksInComments: boolean,
  90. // adminPreferredIndentSize: number,
  91. // isIndentSizeForced: boolean,
  92. rendererSettings: RendererSettings,
  93. growiRendererConfig: GrowiRendererConfig,
  94. // UI
  95. userUISettings: UserUISettingsDocument | null
  96. // Sidebar
  97. sidebarConfig: ISidebarConfig,
  98. };
  99. const GrowiPage: NextPage<Props> = (props: Props) => {
  100. // const { t } = useTranslation();
  101. const router = useRouter();
  102. const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  103. const { data: currentUser } = useCurrentUser(props.currentUser != null ? JSON.parse(props.currentUser) : null);
  104. // register global EventEmitter
  105. if (isClient()) {
  106. (window as CustomWindow).globalEmitter = new EventEmitter();
  107. }
  108. // commons
  109. useAppTitle(props.appTitle);
  110. useSiteUrl(props.siteUrl);
  111. useXss(new Xss());
  112. // useEditorConfig(props.editorConfig);
  113. useConfidential(props.confidential);
  114. useCsrfToken(props.csrfToken);
  115. // UserUISettings
  116. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  117. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  118. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  119. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  120. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  121. // page
  122. useCurrentPagePath(props.currentPathname);
  123. useIsLatestRevision(props.isLatestRevision);
  124. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  125. useIsForbidden(props.isForbidden);
  126. useIsNotFound(props.isNotFound);
  127. // useIsTrashPage(_isTrashPage(props.currentPagePath));
  128. // useShared();
  129. // useShareLinkId(props.shareLinkId);
  130. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  131. useIsSharedUser(false); // this page cann't be routed for '/share'
  132. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  133. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  134. useIsSearchServiceReachable(props.isSearchServiceReachable);
  135. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  136. useIsSlackConfigured(props.isSlackConfigured);
  137. // useIsMailerSetup(props.isMailerSetup);
  138. useIsAclEnabled(props.isAclEnabled);
  139. // useHasSlackConfig(props.hasSlackConfig);
  140. // useDrawioUri(props.drawioUri);
  141. // useHackmdUri(props.hackmdUri);
  142. // useNoCdn(props.noCdn);
  143. // useIndentSize(props.adminPreferredIndentSize);
  144. useRendererSettings(props.rendererSettings);
  145. useGrowiRendererConfig(props.growiRendererConfig);
  146. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  147. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  148. // const { data: editorMode } = useEditorMode();
  149. let pageWithMeta: IPageWithMeta | undefined;
  150. if (props.pageWithMetaStr != null) {
  151. pageWithMeta = JSON.parse(props.pageWithMetaStr) as IPageWithMeta;
  152. }
  153. useCurrentPageId(pageWithMeta?.data._id);
  154. useSWRxCurrentPage(undefined, pageWithMeta?.data); // store initial data
  155. // useSWRxPage(pageWithMeta?.data._id);
  156. useSWRxPageInfo(pageWithMeta?.data._id, undefined, pageWithMeta?.meta); // store initial data
  157. useIsTrashPage(_isTrashPage(pageWithMeta?.data.path ?? ''));
  158. useCurrentPagePath(pageWithMeta?.data.path);
  159. useCurrentPathname(props.currentPathname);
  160. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  161. useEffect(() => {
  162. if (isClient() && window.location.pathname !== props.currentPathname) {
  163. router.replace(props.currentPathname, undefined, { shallow: true });
  164. }
  165. }, [props.currentPathname, router]);
  166. const classNames: string[] = [];
  167. // switch (editorMode) {
  168. // case EditorMode.Editor:
  169. // classNames.push('on-edit', 'builtin-editor');
  170. // break;
  171. // case EditorMode.HackMD:
  172. // classNames.push('on-edit', 'hackmd');
  173. // break;
  174. // }
  175. // if (props.isContainerFluid) {
  176. // classNames.push('growi-layout-fluid');
  177. // }
  178. // if (page == null) {
  179. // classNames.push('not-found-page');
  180. // }
  181. return (
  182. <>
  183. <Head>
  184. {/*
  185. {renderScriptTagByName('drawio-viewer')}
  186. {renderScriptTagByName('mathjax')}
  187. {renderScriptTagByName('highlight-addons')}
  188. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  189. */}
  190. </Head>
  191. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  192. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')}>
  193. <header className="py-0">
  194. {/* <GrowiSubNavigation /> */}
  195. GrowiSubNavigation
  196. </header>
  197. <div className="d-edit-none">
  198. {/* <GrowiSubNavigationSwitcher /> */}
  199. GrowiSubNavigationSwitcher
  200. </div>
  201. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  202. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  203. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  204. <div className="row">
  205. <div className="col">
  206. <div id="content-main" className="content-main grw-container-convertible">
  207. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  208. { !props.isIdenticalPathPage && (
  209. <>
  210. <PageAlerts />
  211. { props.isForbidden
  212. ? <>ForbiddenPage</>
  213. : <DisplaySwitcher />
  214. }
  215. <div id="page-editor-navbar-bottom-container" className="d-none d-edit-block"></div>
  216. {/* <PageStatusAlert /> */}
  217. PageStatusAlert
  218. </>
  219. ) }
  220. </div>
  221. </div>
  222. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  223. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  224. <div id="revision-toc-content" className="revision-toc-content"></div>
  225. </div>
  226. </div> */}
  227. </div>
  228. </div>
  229. <footer>
  230. {/* <PageComments /> */}
  231. PageComments
  232. </footer>
  233. <UnsavedAlertDialog />
  234. </BasicLayout>
  235. </>
  236. );
  237. };
  238. function getPageIdFromPathname(currentPathname: string): string | null {
  239. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  240. }
  241. class MultiplePagesHitsError extends ExtensibleCustomError {
  242. pagePath: string;
  243. constructor(pagePath: string) {
  244. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  245. this.pagePath = pagePath;
  246. }
  247. }
  248. async function getPageData(context: GetServerSidePropsContext, props: Props): Promise<IPageWithMeta|null> {
  249. const req: CrowiRequest = context.req as CrowiRequest;
  250. const { crowi } = req;
  251. const { revisionId } = req.query;
  252. const Page = crowi.model('Page') as PageModel;
  253. const { pageService } = crowi;
  254. const { currentPathname } = props;
  255. const pageId = getPageIdFromPathname(currentPathname);
  256. const isPermalink = _isPermalink(currentPathname);
  257. const { user } = req;
  258. // check whether the specified page path hits to multiple pages
  259. if (!isPermalink) {
  260. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  261. if (count > 1) {
  262. throw new MultiplePagesHitsError(currentPathname);
  263. }
  264. }
  265. const result: IPageWithMeta = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  266. const page = result?.data as unknown as PageDocument;
  267. // populate & check if the revision is latest
  268. if (page != null) {
  269. page.initLatestRevisionField(revisionId);
  270. await page.populateDataToShowRevision();
  271. props.isLatestRevision = page.isLatestRevision();
  272. }
  273. return result;
  274. }
  275. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props, pageWithMeta: IPageWithMeta|null): Promise<void> {
  276. const req: CrowiRequest = context.req as CrowiRequest;
  277. const { crowi } = req;
  278. const Page = crowi.model('Page') as PageModel;
  279. const { currentPathname } = props;
  280. const pageId = getPageIdFromPathname(currentPathname);
  281. const isPermalink = _isPermalink(currentPathname);
  282. const page = pageWithMeta?.data;
  283. if (props.isIdenticalPathPage) {
  284. // TBD
  285. }
  286. else if (page == null) {
  287. props.isNotFound = true;
  288. // check the page is forbidden or just does not exist.
  289. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  290. props.isForbidden = count > 0;
  291. }
  292. else {
  293. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  294. if (isPermalink && page.isEmpty) {
  295. props.currentPathname = page.path;
  296. }
  297. // /path/to/page ==> /62a88db47fed8b2d94f30000
  298. if (!isPermalink && !page.isEmpty) {
  299. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  300. if (!isToppage) {
  301. props.currentPathname = `/${page._id}`;
  302. }
  303. }
  304. }
  305. }
  306. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  307. // const req: CrowiRequest = context.req as CrowiRequest;
  308. // const { crowi } = req;
  309. // const UserModel = crowi.model('User');
  310. // if (isUserPage(props.currentPagePath)) {
  311. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  312. // if (user != null) {
  313. // props.pageUser = JSON.stringify(user.toObject());
  314. // }
  315. // }
  316. // }
  317. async function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): Promise<void> {
  318. const req: CrowiRequest = context.req as CrowiRequest;
  319. const { crowi } = req;
  320. const {
  321. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  322. } = crowi;
  323. props.isSearchServiceConfigured = searchService.isConfigured;
  324. props.isSearchServiceReachable = searchService.isReachable;
  325. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  326. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  327. // props.isMailerSetup = mailService.isMailerSetup;
  328. props.isAclEnabled = aclService.isAclEnabled();
  329. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  330. // props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  331. // props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  332. // props.mathJax = configManager.getConfig('crowi', 'app:mathJax');
  333. // props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  334. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  335. // props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  336. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  337. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  338. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  339. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  340. // props.editorConfig = {
  341. // upload: {
  342. // image: crowi.fileUploadService.getIsUploadable(),
  343. // file: crowi.fileUploadService.getFileUploadEnabled(),
  344. // },
  345. // };
  346. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  347. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  348. props.rendererSettings = {
  349. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  350. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  351. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  352. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  353. };
  354. props.growiRendererConfig = {
  355. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  356. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  357. tagWhiteList: crowi.xssService.getTagWhiteList(),
  358. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  359. plantumlUri: process.env.PLANTUML_URI ?? null,
  360. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  361. };
  362. props.sidebarConfig = {
  363. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  364. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  365. };
  366. }
  367. /**
  368. * for Server Side Translations
  369. * @param context
  370. * @param props
  371. * @param namespacesRequired
  372. */
  373. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  374. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  375. props._nextI18Next = nextI18NextConfig._nextI18Next;
  376. }
  377. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  378. const req: CrowiRequest = context.req as CrowiRequest;
  379. const { user } = req;
  380. const result = await getServerSideCommonProps(context);
  381. // check for presence
  382. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  383. if (!('props' in result)) {
  384. throw new Error('invalid getSSP result');
  385. }
  386. const props: Props = result.props as Props;
  387. let pageWithMeta;
  388. try {
  389. pageWithMeta = await getPageData(context, props);
  390. props.pageWithMetaStr = JSON.stringify(pageWithMeta);
  391. }
  392. catch (err) {
  393. if (err instanceof MultiplePagesHitsError) {
  394. props.isIdenticalPathPage = true;
  395. }
  396. else {
  397. throw err;
  398. }
  399. }
  400. injectRoutingInformation(context, props, pageWithMeta);
  401. injectServerConfigurations(context, props);
  402. injectNextI18NextConfigurations(context, props, ['translation']);
  403. if (user != null) {
  404. props.currentUser = JSON.stringify(user);
  405. }
  406. // UI
  407. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  408. props.userUISettings = JSON.parse(JSON.stringify(userUISettings));
  409. return {
  410. props,
  411. };
  412. };
  413. export default GrowiPage;